package weixin_oauth

import (
	"encoding/json"
	"fmt"
	"io"
	"log/slog"
	"net/http"
)

const (
	SnsapiBase     = "snsapi_base"
	SnsapiUserinfo = "snsapi_userinfo"
)

func httpGet[T any](apiUrl string) (v T, err error) {
	var (
		reqUrl  = apiUrl
		resBody = ""
	)
	defer func() {
		slog.Info(fmt.Sprintf("weixin_oauth API  reqUrl:%s  resBody:%s  ", reqUrl, resBody))
	}()

	resp, err := http.Get(apiUrl)
	if err != nil {
		return
	}
	b, err := io.ReadAll(resp.Body)
	if err != nil {
		return
	}
	resBody = string(b)

	var er ErrResp
	err = json.Unmarshal(b, &er)
	if err != nil {
		return
	}
	if er.Errcode != 0 {
		err = fmt.Errorf("WX%v:%v", er.Errcode, er.Errmsg)
		return
	}
	err = json.Unmarshal(b, &v)
	if err != nil {
		return
	}
	return
}

type ErrResp struct {
	Errcode int64  `json:"errcode"` //失败时才有值
	Errmsg  string `json:"errmsg"`
}
